<?php

namespace App\Http\Controllers;

use App\Models\Customer;
use App\Models\OrderSa;
use App\Models\OrderSaPro;
use App\Models\Product;
use App\Models\Store;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class OrderSaController extends Controller
{
    /**
     * 订单列表
     * GET /api/order-sa
     * @param Request $request
     * @return JsonResponse
     */
    public function index(Request $request): JsonResponse
    {
        $params = $request->all();
        if (empty($params['customer_id'])) {
            return response()->json(['status' => 1009, 'message' => '请先登录']);
        }
        if (empty($params['store_id'])) {
            return response()->json(['status' => 1009, 'message' => '请先登录']);
        }
        if (empty($params['pay_mode'])) {
            return response()->json(['status' => 1009, 'message' => '请先登录']);
        }
        if (empty($params['product_list'])) {
            return response()->json(['status' => 0, 'message' => '下单产品不能为空']);
        }

        // 客户校验
        $customer = Customer::where('id', $params['customer_id'])->first();
        if (empty($customer)) {
            return response()->json(['status' => 0, 'message' => '客户不存在']);
        }
        if ($customer->status != 'NORMAL') {
            return response()->json(['status' => 0, 'message' => '客户已禁用，无法下单']);
        }

        // 门店校验
        $store = Store::where('id', $params['store_id'])->first();
        if (empty($store)) {
            return response()->json(['status' => 0, 'message' => '加购门店不存在']);
        }
        if ($store->status != 'NORMAL') {
            return response()->json(['status' => 0, 'message' => '加购门店未营业']);
        }

        // 查询产品信息
        if (empty(array_column($params['product_list'], 'product_id'))) {
            return response()->json(['status' => 0, 'message' => '下单产品ID不能为空']);
        }
        $product = new Product();
        $query['status'] = 'ENABLE';
        $query['ids'] = array_column($params['product_list'], 'product_id');
        $placeProduct = $product->getList($query);
        $placeProduct = array_column($placeProduct, null, 'id');
        foreach ($params['product_list'] as $key => $item) {
            $pro = $placeProduct[$item['product_id']] ?? [];
            if (empty($pro)) {
                return response()->json(['status' => 0, 'message' => '下单产品不存在']);
            }
            if ($pro->status != 'ENABLE') {
                return response()->json(['status' => 0, 'message' => '下单产品未上架']);
            }
            if (empty($pro->price)) {
                return response()->json(['status' => 0, 'message' => '下单产品未设置价格，无法下单']);
            }
            if (empty($item['count']) || $item['count'] <= 0) {
                return response()->json(['status' => 0, 'message' => '下单产品数量不能为空']);
            }
            $params['product_list'][$key]['price'] = $pro->price;
            $params['product_list'][$key]['pack_price'] = $pro->pack_price;
            $params['product_list'][$key]['total_pack_price'] = round($pro->pack_price * $item['count'], 2);
            $params['product_list'][$key]['total_price'] = round($pro->price * $item['count'], 2);
        }

        $orderId = OrderSa::createOrder('SA');

        // 保存订单
        $orderSa['order_id'] = $orderId;
        $orderSa['take_order_id'] = OrderSa::createOrder('G');
        $orderSa['customer_id'] = $params['customer_id'];
        $orderSa['store_id'] = $params['store_id'];
        $orderSa['store_name'] = $store->name;
        $orderSa['status'] = 'INVALID';
        $orderSa['pay_status'] = 'INVALID';
        $orderSa['origin_price'] = round(array_sum(array_column($params['product_list'], 'total_price')), 2);
        $orderSa['pack_price'] = round(array_sum(array_column($params['product_list'], 'total_pack_price')), 2);
        $orderSa['total_market_price'] = 0;
        $orderSa['market_id'] = 0;
        $orderSa['pay_mode'] = $params['pay_mode'];
        $orderSa['tableware_count'] = $params['tableware_count'] ?? 'wx';
        $orderSa['remark'] = $params['remark'] ?? '';
        $orderSa['create_at'] = time();
        OrderSa::create($orderSa);

        // 保存订单明细
        foreach ($params['product_list'] as $item) {
            $orderSaPro['order_id'] = $orderId;
            $orderSaPro['product_id'] = $item['product_id'];
            $orderSaPro['count'] = $item['count'];
            $orderSaPro['price'] = $item['price'];
            $orderSaPro['total_price'] = $item['total_price'];
            $orderSaPro['market_price'] = $item['market_price'];
            $orderSaPro['create_at'] = time();
            OrderSaPro::create($orderSaPro);
        }

        return response()->json(['status' => 1, 'data' => $orderId]);
    }
}
